package org.suren.littlebird.preferences;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.WorkbenchException;
import org.eclipse.ui.XMLMemento;
import org.osgi.service.prefs.BackingStoreException;

/**
 * @author suren
 * @date 2015-4-3
 *
 * http://surenpi.com
 */
public class SuRenPref
{
	public static final String PREF_SYNC_ROOT = "sync-files";

	InstanceScope instanceScope = new InstanceScope();
	IEclipsePreferences prefs = instanceScope.getNode("org.suren.littlebird");

	public List<String> getSyncList()
	{
		List<String> syncList = new ArrayList<String>();
		String xmlStr = prefs.get("syncList", "");
		if(xmlStr != null && !"".equals(xmlStr))
		{
			try
			{
				StringReader reader = new StringReader(xmlStr);
				XMLMemento memento = XMLMemento.createReadRoot(reader, PREF_SYNC_ROOT);

				IMemento[] fileChildren = memento.getChildren("file");
				if(fileChildren != null)
				{
					for(IMemento fileChild : fileChildren)
					{
						syncList.add(fileChild.getString("path"));
					}
				}
			}
			catch (WorkbenchException e1)
			{
				e1.printStackTrace();
			}
		}

		return syncList;
	}

	public boolean setSyncList(String[] syncFileArray)
	{
		XMLMemento memento = XMLMemento.createWriteRoot(PREF_SYNC_ROOT);
		for(String syncFile : syncFileArray)
		{
			memento.createChild("file").putString("path", syncFile);
		}

		StringWriter writer = new StringWriter();
		try
		{
			memento.save(writer);
			String xmlStr = writer.getBuffer().toString();

			prefs.put("syncList", xmlStr);
			prefs.flush();

			return true;
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		catch (BackingStoreException e)
		{
			e.printStackTrace();
		}

		return false;
	}
}
